class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        acc = 1
        matrix = [[None for _ in range(n)] for _ in range(n)]
        up, down, left, right = 0, n-1, 0, n-1
        while True:
            if up>down or left>right: break
            for c in range(left, right+1):
                matrix[up][c] = acc
                acc+=1
            up+=1
            if up>down or left>right: break
            for r in range(up, down+1):
                matrix[r][right] = acc
                acc+=1
            right-=1
            if up>down or left>right: break
            for c in range(right, left-1, -1):
                matrix[down][c] = acc
                acc+=1
            down-=1
            if up>down or left>right: break
            for r in range(down, up-1, -1):
                matrix[r][left] = acc
                acc+=1
            left+=1
        return matrix

print(Solution().generateMatrix(3))